package biz.alla.market.web.controller;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import biz.alla.market.domain.Application;
import biz.alla.market.domain.Category;
import biz.alla.market.service.MarketService;

@Controller
public class HomeController {
    private MarketService marketService;

    protected static final String MODEL_ATTRIBUTE_APPLICATIONS = "applications";
    protected static final String MODEL_ATTRIBUTE_CATEGORIES = "categories";
    protected static final String HOME_VIEW = "home";

    @RequestMapping("/home")
    public String showHome(@ModelAttribute(MODEL_ATTRIBUTE_CATEGORIES) List<Category> categories, ModelMap modelMap) {
	populateApplications(modelMap, categories.get(0).getId());
	return HOME_VIEW;
    }

    @RequestMapping("/home/applications")
    public String showApplicationsByCategoryId(@RequestParam(value = "categoryId", required = true) int categoryId, ModelMap modelMap) {
	populateApplications(modelMap, categoryId);
	return HOME_VIEW;
    }

    @ModelAttribute(MODEL_ATTRIBUTE_CATEGORIES)
    public List<Category> getCategories() {
	return marketService.getCategories();
    }

    private void populateApplications(ModelMap modelMap, int categoryId) {
	List<Application> applications = marketService.getApplications(categoryId);
	modelMap.addAttribute(MODEL_ATTRIBUTE_APPLICATIONS, applications);
    }

    public void setMarketService(MarketService marketService) {
	this.marketService = marketService;
    }
}
